package com.example.word.ui.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.dict.R;
import com.example.word.adapter.WordReviewAdapter;
import com.example.word.adapter.WordStudyAdapter;
import com.example.word.bean.Browse;
import com.example.word.bean.Collect;
import com.example.word.bean.Word;
import com.example.word.util.CommonUtils;
import com.example.word.util.DateUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.widget.ActionBar;

import org.litepal.crud.DataSupport;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 单词复习
 */
public class WordReviewActivity extends AppCompatActivity {
    private Activity myActivity;
    private ActionBar mTitleBar;//标题栏
    private LinearLayout operationList;
    private RecyclerView recyclerView;
    private WordReviewAdapter wordReviewAdapter;
    private List<Word> wordList = new ArrayList<>();
    public static String account;
    private Button nextWord, preWord;
    private int currentWordIndex;
    private MediaPlayer mediaPlayer;
    private ImageView collect, collect1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_word_review);
        myActivity = this;
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        recyclerView = findViewById(R.id.rv_word_review_list);
        operationList = findViewById(R.id.operationList);
        mTitleBar = (ActionBar) findViewById(R.id.myActionBar);
        nextWord = findViewById(R.id.nextWord);
        nextWord.setText("认识");
        preWord = findViewById(R.id.preWord);
        collect = findViewById(R.id.collect);
        collect1 = findViewById(R.id.collect1);
        mTitleBar.setData(myActivity, "单词复习", R.drawable.ic_back, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            nextWord.setBackground(getResources().getDrawable(R.drawable.btn_border_next2));
            preWord.setBackground(getResources().getDrawable(R.drawable.btn_border_next));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
            nextWord.setBackground(getResources().getDrawable(R.drawable.btn_border_next_my_color2));
            preWord.setBackground(getResources().getDrawable(R.drawable.btn_border_next_my_color));
        }
        initView();
    }

    private void initView() {
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        wordReviewAdapter = new WordReviewAdapter(recyclerView);
        //=2.3、设置recyclerView的适配器
        recyclerView.setAdapter(wordReviewAdapter);
        loadData();//加载数据
        wordReviewAdapter.setItemListener(new WordReviewAdapter.ItemListener() {
            @Override
            public void ukPhoneClick(Word word) {
                playWord(word);
            }

            @Override
            public void usPhoneClick(Word word) {
                usPlayWord(word);
            }

            @Override
            public void titleClick(Word word) {
                playWord(word);
            }
        });
        // 设置不认识按钮点击事件
        preWord.setOnClickListener(v -> {
            // 获取下一个单词
            this.currentWordIndex += 1;
            String currentAndTotalText = (currentWordIndex + 1) + " / " + wordList.size();
            if (currentWordIndex == wordList.size()) {
                // 如果当前是最后一个单词，直接退出页面
                finish();
            } else if (currentWordIndex == (wordList.size() - 1)) {
                // 如果下一个单词是最后一个，显示复习完成按钮
                MessageUtils.show("已将该单词加入下一轮复习", myActivity);
                nextWord.setText("完成复习");
                mTitleBar.setTitle(currentAndTotalText);
                Collect collects = DataSupport.where("account = ? and word = ?", account, wordList.get(this.currentWordIndex).getWord()).findFirst(Collect.class);
                collect.setVisibility(collects != null ? View.GONE : View.VISIBLE);
                collect1.setVisibility(collects != null ? View.VISIBLE : View.GONE);

                Word currentWord = wordList.get(this.currentWordIndex);
                wordReviewAdapter.setCurrentWord(currentWord, account);
            } else {
                MessageUtils.show("已将该单词加入下一轮复习", myActivity);
                nextWord.setText("认识");
                playWord(wordList.get(this.currentWordIndex));
                mTitleBar.setTitle(currentAndTotalText);
                Collect collects = DataSupport.where("account = ? and word = ?", account, wordList.get(this.currentWordIndex).getWord()).findFirst(Collect.class);
                collect.setVisibility(collects != null ? View.GONE : View.VISIBLE);
                collect1.setVisibility(collects != null ? View.VISIBLE : View.GONE);

                Word currentWord = wordList.get(this.currentWordIndex);
                wordReviewAdapter.setCurrentWord(currentWord, account);
            }
        });
        // 设置认识按钮点击事件
        nextWord.setOnClickListener(v -> {
            // 获取下一个单词
            this.currentWordIndex += 1;
            String currentAndTotalText = (currentWordIndex + 1) + " / " + wordList.size();
            if (currentWordIndex == wordList.size()) {
                // 如果当前是最后一个单词，直接退出页面
                Word currentWord = wordList.get(this.currentWordIndex - 1);
                Browse browse = Browse.where("account = ? and word = ?", account, currentWord.getWord()).findFirst(Browse.class);
                browse.setIsReview("Y");
                browse.save();
                finish();
            } else if (currentWordIndex == (wordList.size() - 1)) {
                // 如果下一个单词是最后一个，显示复习完成按钮
                nextWord.setText("完成复习");
                mTitleBar.setTitle(currentAndTotalText);
                Collect collects = DataSupport.where("account = ? and word = ?", account, wordList.get(this.currentWordIndex).getWord()).findFirst(Collect.class);
                collect.setVisibility(collects != null ? View.GONE : View.VISIBLE);
                collect1.setVisibility(collects != null ? View.VISIBLE : View.GONE);

                Word currentWord = wordList.get(this.currentWordIndex);
                Browse browse = Browse.where("account = ? and word = ?", account, currentWord.getWord()).findFirst(Browse.class);
                browse.setIsReview("Y");
                browse.save();

                wordReviewAdapter.setCurrentWord(currentWord, account);
            } else {
                nextWord.setText("认识");
                playWord(wordList.get(this.currentWordIndex));
                mTitleBar.setTitle(currentAndTotalText);
                Collect collects = DataSupport.where("account = ? and word = ?", account, wordList.get(this.currentWordIndex).getWord()).findFirst(Collect.class);
                collect.setVisibility(collects != null ? View.GONE : View.VISIBLE);
                collect1.setVisibility(collects != null ? View.VISIBLE : View.GONE);

                Word currentWord = wordList.get(this.currentWordIndex);
                Browse browse = Browse.where("account = ? and word = ?", account, currentWord.getWord()).findFirst(Browse.class);
                browse.setIsReview("Y");
                browse.save();


                wordReviewAdapter.setCurrentWord(currentWord, account);
            }
        });

        //收藏
        collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Collect collects = new Collect(account, wordList.get(currentWordIndex).getWord(), DateUtils.dateString());
                collects.save();
                MessageUtils.show("收藏成功", myActivity);
                collect.setVisibility(View.GONE);
                collect1.setVisibility(View.VISIBLE);
            }
        });
        //取消
        collect1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Collect collects = DataSupport.where("account = ? and word = ?", account, wordList.get(currentWordIndex).getWord()).findFirst(Collect.class);
                collects.delete();
                MessageUtils.show("取消成功", myActivity);
                collect.setVisibility(View.VISIBLE);
                collect1.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 加载数据
     */
    private void loadData() {
        ProgressDialog dialog = new ProgressDialog(myActivity);
        dialog.setMessage("加载中···");
        dialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 查询当前用户学习过,未复习的单词列表
                List<Browse> browseList = Browse.where("account = ? and isReview != 'Y'", account).find(Browse.class);

                if (browseList.isEmpty()) {
                    MessageUtils.show("未查询到已学习可复习的单词", myActivity);
                    finish();
                    return;
                }

                List<String> wordArray = new ArrayList<>();

                for (Browse browse : browseList) {
                    wordArray.add(browse.getWord());
                }

                StringBuilder wordsWhere = new StringBuilder();
                for (String word : wordArray.toArray(new String[0])) {
                    wordsWhere.append("'").append(word.replace("'", "''")).append("',");
                }
                String inSql = wordsWhere.toString().substring(0, wordsWhere.toString().length() - 1);
                wordList = Word.where("word in (" + inSql + ") group by word").find(Word.class);
                if (wordList.size() == 1) {
                    nextWord.setText("完成复习");
                }
                mTitleBar.setTitle((currentWordIndex + 1) + " / " + wordList.size());

                Word currentWord = wordList.get(currentWordIndex);

                Collect collects = DataSupport.where("account = ? and word = ?", account, currentWord.getWord()).findFirst(Collect.class);
                collect.setVisibility(collects != null ? View.GONE : View.VISIBLE);
                collect1.setVisibility(collects != null ? View.VISIBLE : View.GONE);

                playWord(currentWord);
                wordReviewAdapter.setCurrentWord(currentWord, account);

                dialog.dismiss();
            }
        }, 101);
    }

    // 播放单词
    private void playWord(Word word) {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            mediaPlayer = new MediaPlayer();
        } else
            mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(CommonUtils.wordSingUrl + word.getWord());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    MessageUtils.show("发生错误，请检查网络设置", myActivity);
                    onBackPressed();
                    return true;
                }
            });
        } catch (Exception e) {
            com.example.word.util.ExceptionUtils.printExceptionDetail(e);
        }
    }

    // 美式播放单词
    private void usPlayWord(Word word) {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            mediaPlayer = new MediaPlayer();
        } else
            mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource("https://dict.youdao.com/dictvoice?type=0&audio=" + word.getWord());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    MessageUtils.show("发生错误，请检查网络设置", myActivity);
                    onBackPressed();
                    return true;
                }
            });
        } catch (Exception e) {
            com.example.word.util.ExceptionUtils.printExceptionDetail(e);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }
}